package edu.towson.cosc.cosc455.jirani2.compiler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Scanner;

/*
 * Compiler class to check file, read in, call individual pieces
 * of a compiler, then write to .html file
 */

public class MyCompiler {

	/** Will hold the current token */
	public static String token = ""; 
	/** String that holds contents of .lol */
	public static String fileContents = "";
	/** LexicalAnalyzer object */
	static MyLexicalAnalyzer Lexer;
	/** Syntax object */
	static MySyntaxAnalyzer parser;
	/** Semantic object */
	static MySemanticAnalyzer generator;
	/** ParseTree that holds indv. pieces of .lol file */
	static ArrayList<String> parseTree;
	
	public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
		
		//Check that there is 1 arg
		if(args.length != 1){
			System.err.println("ERROR!, only takes one argument!");
			System.exit(0);
		}
		//Checking last 4 chars in a string are '.lol'
		if(!args[0].toLowerCase().substring(args[0].length()-4, args[0].length()).equals(".lol")){
			System.err.println("Compiler ERROR!, you need a .lol extension!");
			System.exit(0);
		}
		//Reading one by one and storing with space inbetween
		Scanner scanner = new Scanner(new File(args[0]));
		while(scanner.hasNext()) {
			fileContents += scanner.next() + " ";
		}

		LexicalTokens tokes = new LexicalTokens();
		tokes.addTokens();//Adding lexical tokens to a tokArray
		
		parseTree = new ArrayList<String>();
		
		//Call lexical analyzer
		Lexer = new MyLexicalAnalyzer();
		Lexer.getNextToken();
		
		//Call syntax analyzer
		parser = new MySyntaxAnalyzer();
		parser.lolcode();
		
		//Call Semantic Analyzer
		generator = new MySemanticAnalyzer();
		generator.semantic();
		
		String outputFile = args[0].substring(0, args[0].length()-4) + ".html";
		PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
		writer.print(MySemanticAnalyzer.semanticText);
		writer.close();
	}
}
